package com.css.fxfzypg.modules.preassesstaskmanage.service.impl;

import com.css.fxfzypg.modules.group.entity.GroupUserEntity;
import com.css.fxfzypg.modules.group.entity.UserEntity;
import com.css.fxfzypg.modules.group.service.GroupUserService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessTaskGroupVo;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessVo;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessTaskVo;
import com.css.fxfzypg.modules.surveytaskmanage.vo.TaskVo;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.impl.SUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.*;

/**
 * @author
 * @program
 * @description
 * @create 2022/8/8 10:42
 **/
@Service
public class PreAssessTaskServiceImpl implements PreAssessTaskService {
    @Autowired
    PreAssessTaskRepository preAssessTaskRepository;

    @Autowired
    SUserServiceImpl sUserServiceImpl;

    @Autowired
    GroupUserService groupUserService;

    @Override
    @Transactional
    public String saveTask(PreAssessTaskVo preAssessTaskVo) {
        PreAssessTaskEntity parentTask =preAssessTaskVo.getParentTask();
        String userId = PlatformSessionContext.getUserID();
        String parentTaskId = UUIDGenerator.getUUID();
        parentTask.setDelFlag("0");
        parentTask.setCreateUser(userId);
        parentTask.setCreateTime(new Date());
        //获取用户名称
        String sUser = sUserServiceImpl.getSUser(userId);
        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
        String userName=userInfo.getUserName();
        parentTask.setTaskManager(userName);
        parentTask.setId(parentTaskId);
        parentTask.setParentId("0");

        StringBuilder str=new StringBuilder();
        List<String> districtList = parentTask.getDistrictList();
        for(String districts:districtList){
            str.append(districts+"、");
        }
        String district=str.substring(0, str.lastIndexOf("、"));
        parentTask.setTaskDistrict(district);
        if(PlatformObjectUtils.isEmpty(parentTask.getGroupId())){
            parentTask.setTaskStatus("0");
        }else{
            parentTask.setTaskStatus("1");
            String sUser1 = sUserServiceImpl.getSUser(parentTask.getGroupLeaderId());
            SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
            parentTask.setMobilePhone(user.getMobilePhone());
        }

        PreAssessTaskEntity subTask = preAssessTaskVo.getSubTask();
        if(!PlatformObjectUtils.isEmpty(subTask)){
            StringBuilder str1=new StringBuilder();
            List<String> subTaskdistricts = subTask.getDistrictList();

            for(String subTaskdistrict:subTaskdistricts){
                for(String districts:districtList){
                    if(districts.contains(subTaskdistrict)){
                        str1.append(districts+"、");
                    }
                }
            }
            String subDistrict=str1.substring(0, str1.lastIndexOf("、"));
            subTask.setTaskDistrict(subDistrict);

            subTask.setDelFlag("0");
            subTask.setCreateUser(userId);
            subTask.setCreateTime(new Date());
            //获取用户名称
            subTask.setTaskManager(userName);
            subTask.setId(UUIDGenerator.getUUID());
            subTask.setParentId(parentTaskId);
            subTask.setParentTask(parentTask.getTaskNum());
            if(PlatformObjectUtils.isEmpty(subTask.getGroupId())){
                subTask.setTaskStatus("0");
            }else{
                parentTask.setTaskStatus("1");
                subTask.setTaskStatus("1");
                String sUser1 = sUserServiceImpl.getSUser(subTask.getGroupLeaderId());
                SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
                subTask.setMobilePhone(user.getMobilePhone());
            }
            preAssessTaskRepository.saveTask(subTask);
        }
        preAssessTaskRepository.saveTask(parentTask);
        return parentTaskId;
    }

    @Override
    @Transactional
    public void saveSubTask(PreAssessTaskEntity subTask) {
        if(!PlatformObjectUtils.isEmpty(subTask) ){
            subTask.setDelFlag("0");
            subTask.setCreateUser(PlatformSessionContext.getUserID());
            subTask.setCreateTime(new Date());
            //获取用户名称
            String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            subTask.setTaskManager(userInfo.getUserName());
            subTask.setId(UUIDGenerator.getUUID());
            if(PlatformObjectUtils.isEmpty(subTask.getGroupId())){
                subTask.setTaskStatus("0");
            }else{
                preAssessTaskRepository.completeTask("1",subTask.getParentId());
                subTask.setTaskStatus("1");
                String sUser1 = sUserServiceImpl.getSUser(subTask.getGroupLeaderId());
                SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
                subTask.setMobilePhone(user.getMobilePhone());
            }
            preAssessTaskRepository.saveTask(subTask);
        }
    }

    @Override
    public Map<String,Object> getPage(TaskVo taskVo,int curPage,int pageSize) {
        taskVo.setCreateUser(PlatformSessionContext.getUserID());
        Map<String,Object> parentTask=preAssessTaskRepository.findParentIdByTask("0",taskVo, curPage, pageSize);
        List<PreAssessVo> tasks = (List<PreAssessVo>) parentTask.get("rows");
        for(PreAssessVo task:tasks){
            List<PreAssessVo> subTasks=getSubTasks(task.getId(),taskVo);
            task.setChildren(subTasks);
        }
        return parentTask;
    }

    private List<PreAssessVo> getSubTasks(String id,TaskVo taskVo) {
        List<PreAssessVo> tasks=preAssessTaskRepository.findSubIdByTask(id,taskVo);
        if(tasks!=null) {
            for(PreAssessVo task:tasks) {
                String id1 = task.getId();
                List<PreAssessVo> subTask=preAssessTaskRepository.findSubIdByTask(id1,taskVo);
                task.setChildren(subTask);
            }
        }
        return tasks;
    }

    @Override
    public List<PreAssessTaskEntity> getSubTask(String parentTaskId) {
        List<PreAssessTaskEntity> subTaskList =new ArrayList<>();
        if(!PlatformObjectUtils.isEmpty(parentTaskId)){
            subTaskList =preAssessTaskRepository.getSubTask(parentTaskId);
            return subTaskList;
        }
        return subTaskList;
    }

    @Override
    public PreAssessTaskGroupVo findById(String taskId) {
        PreAssessTaskGroupVo preAssessTaskGroupVo=new PreAssessTaskGroupVo();
        PreAssessTaskEntity preAssessTaskEntity=preAssessTaskRepository.findById(taskId);
        preAssessTaskGroupVo.setPreAssessTaskEntity(preAssessTaskEntity);

        List<UserEntity> memberList=new ArrayList<>();
        List<UserEntity> expertList=new ArrayList<>();

        List<GroupUserEntity> groupUserEntityList=groupUserService.selectGroupMemberAndGroupExpert(preAssessTaskEntity.getGroupId());

        for(GroupUserEntity groupUserEntity:groupUserEntityList){
            String groupUserInfo = sUserServiceImpl.getGroupUserInfo(groupUserEntity.getUserId());
            UserEntity userInfo = CreateGson.createGson().fromJson(groupUserInfo, UserEntity.class);
            if("0".equals(groupUserEntity.getRole())){
                memberList.add(userInfo);
            }else{
                expertList.add(userInfo);
            }
        }
        preAssessTaskGroupVo.setMemberlist(memberList);
        preAssessTaskGroupVo.setExpertlist(expertList);
        return preAssessTaskGroupVo;
    }

    @Override
    public void updateTask(PreAssessTaskEntity preAssessTaskEntity) {
        preAssessTaskEntity.setUpdateTime(new Date());
        preAssessTaskEntity.setUpdateUser(PlatformSessionContext.getUserID());
        preAssessTaskRepository.updateTask(preAssessTaskEntity);
    }

    @Override
    @Transactional
    public void assignGroup(PreAssessTaskEntity preAssessTaskEntity) {
        preAssessTaskEntity.setUpdateUser(PlatformSessionContext.getUserID());
        preAssessTaskEntity.setUpdateTime(new Date());
        if(!PlatformObjectUtils.isEmpty(preAssessTaskEntity.getGroupId())){
            String sUser1 = sUserServiceImpl.getSUser(preAssessTaskEntity.getGroupLeaderId());
            SUser user = CreateGson.createGson().fromJson(sUser1, SUser.class);
            preAssessTaskEntity.setMobilePhone(user.getMobilePhone());
            preAssessTaskEntity.setTaskStatus("1");
            if(!"0".equals(preAssessTaskEntity.getParentId())){
                preAssessTaskRepository.completeTask("1",preAssessTaskEntity.getParentId());
            }
        }
        preAssessTaskRepository.assignGroup(preAssessTaskEntity);
    }

    @Override
    public String getSubTaskCode(String parentTaskNum) {
        StringBuilder stringBuilder = new StringBuilder(parentTaskNum+"-");
        String subNum="";
        DecimalFormat decimalFormat=new DecimalFormat("000");
        PreAssessTaskEntity parentTask=preAssessTaskRepository.getParentTask(parentTaskNum);
        if(!PlatformObjectUtils.isEmpty(parentTask)){
            List<PreAssessTaskEntity> subTask = preAssessTaskRepository.getSubTask(parentTask.getId());
            if(!PlatformObjectUtils.isEmpty(subTask)){
                String maxSubTaskCNum=preAssessTaskRepository.getMaxSubTaskCNum(parentTaskNum);
                String str = maxSubTaskCNum.substring(11, maxSubTaskCNum.length());
                int i = Integer.parseInt(str)+1;
                subNum=decimalFormat.format(i);
            }else{
                int i = 1;
                subNum=decimalFormat.format(i);
            }
        }else{
            int i = 1;
            subNum=decimalFormat.format(i);
        }
        return stringBuilder.append(subNum).toString();
    }

    @Override
    public String getSubTaskDistrict(List<String> taskDistricts) {
        StringBuilder str=new StringBuilder();
        for(String taskDistrict:taskDistricts){
            if(taskDistrict.indexOf("省")!=-1){
                str.append(taskDistrict+",");
            }else if("北京市".equals(taskDistrict) || "天津市".equals(taskDistrict) || "上海市".equals(taskDistrict) || "重庆市".equals(taskDistrict) ||
                    "内蒙古自治区".equals(taskDistrict) || "广西壮族自治区".equals(taskDistrict) || "西藏自治区".equals(taskDistrict) || "宁夏回族自治区".equals(taskDistrict) ||
                    "新疆维吾尔自治区".equals(taskDistrict) || "香港特别行政区".equals(taskDistrict) || "澳门特别行政区".equals(taskDistrict)){
                str.append(taskDistrict+",");
            }
        }
        String subTaskDistrict = str.substring(0, str.lastIndexOf(","));
        return subTaskDistrict;
    }

    @Override
    @Transactional
    public void deleteTask(List<String> list) {
        for(String id:list){
            PreAssessTaskEntity preAssessTaskEntity = preAssessTaskRepository.findById(id);
            if("0".equals(preAssessTaskEntity.getParentId())){
                List<PreAssessTaskEntity> subTaskList = preAssessTaskRepository.getSubTask(preAssessTaskEntity.getId());
                if(!PlatformObjectUtils.isEmpty(subTaskList)){
                    for(PreAssessTaskEntity subTask:subTaskList){
                        preAssessTaskRepository.deleteTask("1",subTask.getId());
                    }
                }
            }
            preAssessTaskRepository.deleteTask("1",preAssessTaskEntity.getId());
        }
    }
}
